package com.crp.unitalinforbaseplat.app.core

import com.crp.unitalinforbaseplat.app.unitalinforbaseplat.entity.Principal
import org.apache.shiro.SecurityUtils
import org.apache.shiro.authc.AuthenticationException
import org.apache.shiro.authz.UnauthorizedException
import org.springframework.http.HttpStatus
import org.springframework.web.bind.annotation.ExceptionHandler
import org.springframework.web.bind.annotation.ResponseStatus
import org.springframework.web.servlet.ModelAndView
import java.io.IOException
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

open class BaseController{

    @ExceptionHandler(AuthenticationException::class, UnauthorizedException::class)
    fun authenticationException(request: HttpServletRequest, response: HttpServletResponse): ModelAndView? {
        if (Servlets.isAjaxRequest(request)) {
            try {
                response.writer.print("nopemission")
            } catch (var4: IOException) {
            }

            return null
        } else {
            return ModelAndView("redirect:/error/403.jsp")
        }
    }

    @ExceptionHandler(Exception::class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    fun handleException(ex: Exception, request: HttpServletRequest, response: HttpServletResponse) {
        try {
            ex.printStackTrace()
            response.writer.print("exception")
        } catch (var5: Exception) {
            var5.printStackTrace()
        }

    }

    protected fun getId(): Long? {
        val subject = SecurityUtils.getSubject()
        val principal = subject.principal as Principal
        return if (principal != null) principal.id else 0L
    }

    protected fun getUserId(): String {
        val subject = SecurityUtils.getSubject()
        val principal = subject.principal as Principal
        return if (principal != null) principal.userId else ""
    }

    protected fun getUserName(): String {
        val subject = SecurityUtils.getSubject()
        val principal = subject.principal as Principal
        return if (principal != null) principal.userId else ""
    }

    protected fun getLoginUserInfo(): Principal {
        val subject = SecurityUtils.getSubject()
        return subject.principal as Principal
    }

    protected fun getCompanyId(): String {
        val subject = SecurityUtils.getSubject()
        val principal = subject.principal as Principal
        return if (principal != null) principal.compayId else ""
    }

    protected fun getDeptId(): String {
        val subject = SecurityUtils.getSubject()
        val principal = subject.principal as Principal
        return if (principal != null) principal.deptId else ""
    }

    protected fun getRoleName():String{
        val subject = SecurityUtils.getSubject()
        val principal = subject.principal as Principal
        return if (principal != null) principal.roleName else ""
    }

}